/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div>
  <div v-if="this.nowNumber === 1" class="optimizetype">
      <span>{{$t('openatccomponents.pattern.optimizetype')}}</span>
      <el-select v-model="value" clearable :placeholder="$t('openatccomponents.common.select')">
        <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="$t('openatccomponents.overview.type' + item.value)"
            :value="item.value"
            >
        </el-option>
        </el-select>
        <span class="optimiNum">{{$t('openatccomponents.pattern.optimizecycle')}}</span>
        <el-input v-model="optimizecycle" clearable :placeholder="$t('openatccomponents.common.enter')"></el-input>
      <el-button type="primary" @click="optimize()">{{$t('openatccomponents.pattern.inoptimize')}}</el-button>
    </div>
    <div class="common-board-column" style="margin-top: 50px;">
      <div class="common-board-column-header">
        {{headerText}}
      </div>
      <div class="common-board-table-header">
        <el-row :gutter="5">
          <el-col :span="2">{{this.$t('openatccomponents.overview.id')}}
          </el-col>
          <el-col :span="4">{{this.$t('openatccomponents.overview.phase')}}
          </el-col>
          <el-col :span="9">{{this.$t('openatccomponents.overview.flow')}}
          </el-col>
          <el-col :span="9">{{this.$t('openatccomponents.overview.saturationflow')}}
          </el-col>
        </el-row>
      </div>
      <draggable
        class="common-board-column-content"
        :list="stageData"
        :options="options">
        <div class="common-board-item" v-for="element in stageData" :key="element.id">
          <el-row :gutter="5">
            <el-col :span="2">
              {{element.id}}
            </el-col>
            <el-col :span="4">
              <el-tooltip class="item" effect="dark" placement="left">
                <div slot="content">{{element.name}}</div>
                <div class="common-phase-description">
                  <xdrdirselector v-if="element.desc.length > 0" Width="70px" Height="70px" Widths="58px" Heights="58px" :Datas="styles" :Data="showStyle" :showlist="element.desc" :ISActiveMask="ISActiveMask" :MaskColor="MaskColor"></xdrdirselector>
                </div>
              </el-tooltip>
          </el-col>
          <el-col :span="9">
              <el-input-number :controls="false" class="col-content" size="small"  :step="1" v-model.number="element.flowperhour" ref="type" :disabled="element.mode === 7"></el-input-number>
          </el-col>
          <el-col :span="9">
              <el-input-number :controls="false" class="col-content" size="small"  :step="1" v-model.number="element.saturation" ref="types" :disabled="element.mode === 7"></el-input-number>
          </el-col>
          </el-row>
        </div>
      </draggable>
  </div>
</div>
</template>
<script>
import draggable from 'vuedraggable'
import { getDuration } from '../../../api/cross'
import xdrdirselector from '../XRDDirSelector/XRDDirSelector'

export default {
  name: 'StageOptimize',
  components: {
    draggable,
    xdrdirselector
  },
  data () {
    return {
      showStyle: {
        left: '2px',
        top: '0px'
      },
      styles: {
        left: '1px',
        top: '0px'
      },
      typeOptions: [{
        value: 'flow-split-opt'
      }, {
        value: 'cycle-opt'
      }],
      value: '',
      optimizecycle: 0
    }
  },
  props: {
    headerText: {
      type: String,
      default: 'Header'
    },
    contrloType: {
      type: String
    },
    stageData: {
      type: Array
    },
    stagesChange: {
      type: Array
    },
    id: {
      type: Number
    },
    rings: {
      type: Object
    },
    nowNumber: {
      type: Number
    },
    phaseList: {
      type: Array
    },
    options: {
      type: Object,
      default () {
        return {}
      }
    },
    list: {
      type: Array,
      default () {
        return []
      }
    },
    // index: {
    //   type: Number
    // },
    ISActiveMask: {
      type: Boolean,
      default: true
    },
    // 当phase的描述为空时，显示的图形颜色。
    MaskColor: {
      type: String,
      default: '#000000'
    }
  },
  created () {
    // this.addMinSplit()
    this.addMin()
  },
  watch: {
    list: {
      handler: function () {
        this.addMin()
        // let list = this.$refs.type
        // let flow = this.$refs.types
        // console.log(this.list, 'list')
        // let cycle = 0
        // let n = this.index
        // for (let i = 0; i < list.length; i++) {
        //   cycle = cycle + Number(list[i].currentValue)
        // }
        // const globalParamModel = this.$store.getters.globalParamModel
        // // let MaxCycle = globalParamModel.getParamsByType('patternList')[n].cycle
        // let pattern = globalParamModel.getParamsByType('patternList')[n]
        // globalParamModel.getParamsByType('patternList')[n].cycle = this.getMaxCycle(pattern)
        // this.addMinSplit()
        // this.$emit('handleSplit', n)
      },
      deep: true
    },
    stageData: {
      handler: function () {
        this.addMins()
        // let list = this.$refs.type
        // let flow = this.$refs.types
        // console.log(this.list, 'list')
        // let cycle = 0
        // let n = this.index
        // for (let i = 0; i < list.length; i++) {
        //   cycle = cycle + Number(list[i].currentValue)
        // }
        // const globalParamModel = this.$store.getters.globalParamModel
        // // let MaxCycle = globalParamModel.getParamsByType('patternList')[n].cycle
        // let pattern = globalParamModel.getParamsByType('patternList')[n]
        // globalParamModel.getParamsByType('patternList')[n].cycle = this.getMaxCycle(pattern)
        // this.addMinSplit()
        // this.$emit('handleSplit', n)
      },
      deep: true
    }
  },
  methods: {
    optimize () {
      let _that = this
      let newPha = []
      for (let i = 0; i < _that.rings.rings.length; i++) {
        newPha.push(..._that.rings.rings[i])
      }
      let phaseData = newPha.map(item => {
        return {
          id: item.id,
          flowperhour: item.flowperhour,
          saturation: item.saturation
        }
      })
      //   let patternList = _that.$store.state.globalParam.tscParam.patternList
      //   console.log(patternList, 'patternList')
      let pattern = _that.rings
      let reqData = {
        'type': _that.value,
        'optcycle': _that.optimizecycle,
        'phaseList': _that.phaseList,
        'pattern': pattern,
        'phases': phaseData
      }
      let isValidata = []
      for (let j = 0; j < newPha.length; j++) {
        let comNum = (newPha[j].length / 4) * 1700 * 0.8
        isValidata.push(newPha[j].flowperhour > comNum)
      }
      if (isValidata.includes(true)) {
        this.$confirm(this.$t('openatccomponents.overview.maxFlow'),
          this.$t('openatccomponents.common.alarm'), {
            confirmButtonText: this.$t('openatccomponents.common.confirm'),
            cancelButtonText: this.$t('openatccomponents.common.cancel'),
            type: 'warning'
          }).then(() => {
          getDuration(reqData).then(data => {
            if (data.data.success) {
              _that.$message({
                type: 'success',
                message: _that.$t('openatccomponents.pattern.success')
              })
              for (let i = 0; i < _that.stagesChange.length; i++) {
                if (_that.stagesChange[i].key === data.data.data.phase[i].id - 1) {
                  _that.stagesChange[i].stageSplit = data.data.data.phase[i].duration
                }
              }
              this.$emit('optimizestage', this.id)
            }
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => {
        })
      } else {
        getDuration(reqData).then(data => {
          if (data.data.success) {
            _that.$message({
              type: 'success',
              message: _that.$t('openatccomponents.pattern.success')
            })
            for (let i = 0; i < _that.stagesChange.length; i++) {
              if (_that.stagesChange[i].key === data.data.data.phase[i].id - 1) {
                _that.stagesChange[i].stageSplit = data.data.data.phase[i].duration
              }
            }
            this.$emit('optimizestage', this.id)
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    addMins () {
      for (let i of this.stageData) {
          if (!i.flowperhour || !i.saturation) {
            i.flowperhour = 0
            i.saturation = 1700
            i.length = this.list.length
          }
      }
    },
    addMin () {
      for (let i of this.list) {
        if (!i.flowperhour || !i.saturation) {
          i.flowperhour = 0
          i.saturation = 1700
          i.length = this.list.length
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.col-content {
  width: 100%;
}
.optimizetype{
  position: absolute;
  margin:0 0 10PX 0;
  .el-input {
    width: 80PX;
  }
  .el-select{
    width: 145PX;
  }
  .el-button {
    margin-left: 10PX;
  }
  .optimiNum {
    padding-left: 10PX;
  }
}
</style>
